#pragma once

#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
#include <functional>



namespace ThreadModle
{
    //typedef void(*func_t)(const std::string &name);
    using func_t = std::function<void(const std::string &name)>;

    class Thread
    {
    
    
    public:
    void Excute()
    {
        isRunning = true;
        _func(_name);
        isRunning = false;
    }
    public:
    Thread(const std::string &name, func_t func)
    :_name(name)
    ,_func(func)
    {
        std::cout<<"create thread..."<<std::endl;
    }

    static void* ThreadRointe(void *args)
    {
        Thread *self = static_cast<Thread*>(args);
        self->Excute();
        std::cout<<"new thread start"<<std::endl;
        return nullptr;
    }
    // 创建线程
    bool Start()
    {
        int n = pthread_create(&_tid,nullptr,ThreadRointe,this);
        if(n != 0) return false;
        return true;
    }
    // 终止线程
    void Stop()
    {
        if(isRunning)
        {
            pthread_cancel(_tid);
            isRunning = false;
            std::cout<<"new thread stop"<<std::endl;
        }
    }
    // 等待线程
    void join()
    {
        if(!isRunning)
        {
            pthread_join(_tid,nullptr);
            std::cout<<"new thread join success"<<std::endl;
        }
    }
    // 线程状态
    std::string Status()
    {
        if(isRunning) return "running";
        return"sleep";
    }
    std::string Name()
    {
        return _name;
    }

    ~Thread()
    {}

    private:
    std::string _name;
    pthread_t _tid;
    bool isRunning;
    func_t _func;
    };
}